package com.example.goodpet.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Handler;
import android.os.Process;
import android.view.View;
import android.widget.Toast;

public class UIUtils {
    public static Context getContext(){
        return MyApplication.context;
    }

    public static Handler getHandler(){
        return MyApplication.handler;
    }

    public static View getView(int viewId){
        return View.inflate(getContext(),viewId,null);
    }

    public static String[] getStringArr(int arrId){
        return getContext().getResources().getStringArray(arrId);
    }
    public static Bitmap zoomImg(Bitmap bm,int newWidth,int newHeight){
        Bitmap newbm = null;
        if (bm!=null){
            // 获得图片的宽高
            int width = bm.getWidth();
            int height = bm.getHeight();
            // 计算缩放比例
            float scaleWidth = ((float) newWidth) / width;
            float scaleHeight = ((float) newHeight) / height;
            // 取得想要缩放的matrix参数
            Matrix matrix = new Matrix();
            matrix.postScale(scaleWidth, scaleHeight);
            // 得到新的图片
            newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        }
        return newbm;
    }
    //与屏幕分辨率相关的
    public static int dp2px(int dp){
        //获取手机密度
        float density = getContext().getResources().getDisplayMetrics().density;
        return (int) (density * dp + 0.5);//实现四舍五入
    }

    public static int px2dp(int px){
        float density = getContext().getResources().getDisplayMetrics().density;
        return (int) (px / density + 0.5);//实现四舍五入
    }
    //  保证代码在主线程中运行
    public static void runOnUiThread(Runnable runnable){
        int id = Process.myPid();
        if (id== MyApplication.mainThreadId){
            runnable.run();
        }else {
            getHandler().post(runnable);
        }
    }
    public static void toast(String msg,boolean isLong){
        Toast.makeText(getContext(), msg, isLong?Toast.LENGTH_LONG:Toast.LENGTH_SHORT).show();
    }
}
